/*
 * Copyright 2017 Baiyyy
 * @(#)JwtApiInterceptor.java
 */

package com.byyy.ccts.core.interceptor;

import com.byyy.ccts.core.mapper.JsonMapper;
import com.byyy.ccts.core.model.AjaxJson;
import com.byyy.ccts.core.utils.JwtUtils;
import com.byyy.ccts.modules.sys.utils.UserUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by DELL on 2019-9-4.
 */
public class JwtApiInterceptor implements HandlerInterceptor {

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object,
                                Exception exception) throws Exception {

    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object,
                           ModelAndView modelAndView) throws Exception {

    }

    /**
     * 验证token请求
     *
     * @param request
     * @param response
     * @param object
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        try {
            String token = request.getHeader("Authorization");
            String username = JwtUtils.parseJWT(token).get("username", String.class);
            UserUtils.getByUserName(username);
            if (username == null) {
                return false;
            }
        } catch (Exception e) {
            AjaxJson json = new AjaxJson();
            json.setRet(AjaxJson.RET_JWT_AUTH_FAIL);
            json.setMsg("登录已过期，请退出重新登录后再进行操作！");
            JsonMapper jsonMapper = new JsonMapper();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.getOutputStream().write(jsonMapper.toJson(json).getBytes("UTF-8"));
            return false;
        }

        return true;
    }

}
